use std::{collections::HashMap, vec};

use model_graph_types::{
    connector::{Connector, QueryOptions},
    database::DataSource,
    extractor::{DataValueSet, ExtractByClassFromDatabaseOption, PageInfor},
    modeling::{Class, Value, ValueType},
};

use sqlite_connector::SqliteConnector;

/// 根据类信息，从数据库中提取到数据
pub async fn extract_by_class_from_database(
    class: &Class,
    data_source: &DataSource,
    options: ExtractByClassFromDatabaseOption,
) -> anyhow::Result<DataValueSet<Class, PageInfor>> {
    //连接数据库
    let connector = SqliteConnector::open(&data_source).await?;

    //执行语句获取到元数据
    let sql = super::get_select_by_class(class).await?;

    let (_, result_values) = connector.query(&sql, &vec![], QueryOptions {}).await?;
    tracing::debug!("result:{:?}", result_values);

    let mut classes: Vec<Value> = vec![];

    for value in result_values {
        //每一个表
        match value {
            Value::Array(cols) => {
                let mut class = HashMap::<String, Value>::new();

                class.insert(
                    String::from("identity"),
                    cols.get(1).map_or(Value::None, |f| f.clone()),
                );

                classes.push(Value::Object(class));
            }
            _ => {
                tracing::debug!("==");
            }
        }
    }

    Ok(DataValueSet {
        meta_data: None,
        headers: None,
        data: classes,
    })
}

fn _get_attribute_type(str: &str) -> ValueType {
    match str {
        "TIMESTAMP" => ValueType::Timestamp,
        "TEXT" => ValueType::String,
        "BIGINT" => ValueType::Number,
        "INTEGER" => ValueType::Number,
        "BLOB" => ValueType::Bytes,
        "BOOLEAN" => ValueType::Boolean,
        _ => {
            tracing::error!("没有对应的数据类型:{}", str);
            ValueType::String
        }
    }
}
